<?php
/**
 *  @department : Commercial development.
 *  @description : This file is part of [example].
 *  example all rights reserved.
 */
use app\common\exception\ApiException;
use app\common\exception\ParamsException;
use app\common\exception\RuntimeException;
use app\common\exception\ValidationException;
use think\Cache;

if (!function_exists('errorException')) {
    /**
     * 抛出异常处理.
     *
     * @param int   $code      异常编码
     * @param array $params    参数
     * @param int   $type      抛出异常类型(0 通用错误; 1 系统支持错误; 2: 参数错误  3:运行错误 4、有效性错误)
     * @param bool  $returnMsg 是否返回错误信息
     *
     * @throws ParamsException
     * @throws ValidationException
     * @throws RuntimeException
     * @throws ApiException
     * @throws Exception
     *
     * @return string|void
     */
    function errorException( $code,  $type = 1,  $params = [],  $returnMsg = '')
    {
        $tipMsg = config('error_message.');
        $msg = isset($tipMsg[$code]) ? $tipMsg[$code] : '错误信息提示不存在';

        if (!empty($params)) {
            foreach ($params as $key => $param) {
                $msg = str_replace("#{$key}#", $param, $msg);
            }
        }

        if ($returnMsg) {
            return $msg;
        }

        switch ($type) {
            case 1:
                throw new \Exception($msg, $code);
                break;
            case 2:
                throw new ParamsException($msg, $code);
                break;
            case 3:
                throw new ApiException($msg, $code);
                break;
            case 4:
                throw new ValidationException($msg, $code);
                break;
            case 5:
                throw new RuntimeException($msg, $code);
                break;
            default:
                throw new \Exception($msg, $code);
                break;
        }
    }
}

if (!function_exists('logWrite')) {
    /**
     * 日志记录.
     *
     * @param int       $code   日志code，当code=99时，需要推送邮件
     * @param Exception $e      异常对象
     * @param string    $logMsg 日志信息
     * @param array     $data   日志数据
     */
    function logWrite( $code, $e = null,  $logMsg,  $data = [])
    {
        try {
            if (empty($e) && empty($logMsg)) {
                return false;
            }

            if (!empty($e)) {
                $logData = [
                    'file'    => $e->getFile(),
                    'line'    => $e->getLine(),
                    'message' => $e->getMessage(),
                    'data'    => json_encode($e->getTrace()),
                ];
            } else {
                $logData = [
                    'message' => $logMsg,
                    'data'    => !empty($data) ? json_encode($data) : '',
                ];
            }

            /** @var LogRecordService $logRecordSrv */
            $logRecordSrv = app(LogRecordService::class);
            $insertData = $logData;
            /* 增加信息记录 */
            $insertData['code'] = $code;
            $insertData['level'] = (99 == $code) ? 'push' : 'error';
            $logRecordSrv->insert($insertData);
        } catch (Exception $e) {
        }

        return false;
    }
}

if (!function_exists('clearLogin')) {
    /**
     * 通过session_id清除登录信息.
     *
     * @param string $sessionId  用户session_id
     * @param int    $reasonType 清除原因(1:在别处被登录;2:权限调整;)
     */
    function clearLogin( $sessionId,  $reasonType)
    {
        //退出清空session
        session(null);

        //清除集群公用的缓存id
        /** @var \service\RedisService $redisSrv */
        $redisSrv = app(\service\RedisService::class);

        $rs = $redisSrv->deleteRedis($sessionId);

        if ($rs) {
            /* 缓存过期原因，用于提示 */
            cache($sessionId, $reasonType, 600);
        }

        return $rs;
    }
}
